package com.ajnp.springcloud.filters;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.apache.bcel.generic.RET;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

@Component
@Slf4j
public class GatewayFilter implements GlobalFilter, Ordered {
    //全局过滤器  拦截所有请求  每当请求进来是 判断是不是带着 uname属性 并且不为空
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("***************come in GatewayFilter:  " + new Date());

        //获取请求中是否包含uname属性
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (uname == null) {
            log.info("********用户名为null，非法用户 ,准备动手 (￢︿̫̿￢☆)");
            //设置被拦截原因 并返回
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            //驳回请求
            return exchange.getResponse().setComplete();
        }
        //条件符合则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
